package crypto.GM;

import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

public class SM4Util {
    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }
    }

    public static void main(String[] args) throws Exception{
        byte[] rawText = "rawText".getBytes();
        byte[] key = Hex.decode("0123456789abcdeffedcba9876543210");
        byte[] cipher = Hex.decode("595298c7c6fd271f0402f804c33d3f66");
        byte[] bs = sm4Encrypt(key, rawText);
        System.out.println(Hex.toHexString(bs));;
        bs = sm4Decrypt(key, bs);
        System.out.println(Hex.toHexString(bs));
    }

    public static byte[] sm4Encrypt(byte[] keyBytes, byte[] rawText) throws Exception{
        if(keyBytes.length != 16) throw new RuntimeException("err key length");
        //if(rawText.length % 16 != 0) throw new RuntimeException("err data length");

        Key key = new SecretKeySpec(keyBytes, "SM4");
        //Cipher out = Cipher.getInstance("SM4Util/ECB/NoPadding", "BC");  // rawText.length % 16 == 0
        Cipher out = Cipher.getInstance("SM4/ECB/PKCS5Padding", "BC");
        out.init(Cipher.ENCRYPT_MODE, key);
        return out.doFinal(rawText);
    }

    public static byte[] sm4Decrypt(byte[] keyBytes, byte[] cipherText) throws Exception {
        if(keyBytes.length != 16) throw new RuntimeException("err key length");
        if(cipherText.length % 16 != 0) throw new RuntimeException("err data length");

        Key key = new SecretKeySpec(keyBytes, "SM4");
        Cipher in = Cipher.getInstance("SM4/ECB/NoPadding", "BC");
        in.init(Cipher.DECRYPT_MODE, key);
        return in.doFinal(cipherText);
    }
}
